package com.oda.camera;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.activity.colza.R;
import com.oda.camera.TakeActivity.PlanetFragment;
import com.oda.camera.util.AlbumStorageDirFactory;
import com.oda.camera.util.BaseAlbumDirFactory;
import com.oda.camera.util.FroyoAlbumDirFactory;
import com.oda.camera.util.IMenu;
import com.oda.camera.util.ISendImage;
import com.oda.camera.util.LoadImage;
import com.oda.camera.util.MyAdapter;
import com.oda.camera.util.PathFile;
import com.oda.camera.util.SavePath;
import com.oda.camera.util.SendImage;
import com.oda.colza.util.SystemUiHider;
import com.oda.user.LoginActivity;

public class ODA_Capture_ctivity extends Activity{
	/**
	 * int to get result
	 */
	private static final int ACTION_TAKE_PHOTO_B = 1;
	private static final String BITMAP_STORAGE_KEY = "viewbitmap";
	private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";

	/**
	 * To store bitmap image
	 */
	private Bitmap mImageBitmap;
	private PathFile linkToAllImage;

	/**
	 * The view
	 */
	private ImageView mImageView;
	private GridView mgrid;

	/**
	 * The Current path
	 */
	private String mCurrentPhotoPath;

	/**
	 * Prefix and Suffix of image's name
	 */
	private static final String JPEG_FILE_PREFIX = "COLZA_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	/**
	 * Class for Album
	 */
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
	private ISendImage selectedImage = null;

	/**
	 * The Drawer view
	 */
	private DrawerLayout mDrawerLayout;

	/**
	 * The listView for Drawer
	 */
	private ListView mDrawerList;

	/**
	 * Action Bat Toggle
	 */
	private ActionBarDrawerToggle mDrawerToggle;

	/**
	 * Title
	 */
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;

	/**
	 * Menu title
	 */
	private String[] menuTitles;
	
	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	
	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;
	
	/**
	 * connection state
	 */
	private boolean isConnected=true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_capture);
		
		
		mImageView = (ImageView) findViewById(R.id.imageView1);
		mgrid = (GridView) findViewById(R.id.gridview);
		
		
		mSystemUiHider = SystemUiHider.getInstance(this, mgrid,HIDER_FLAGS);
		mSystemUiHider.setup();
		
		
		if (this.init()!=null) {
			linkToAllImage = this.init();
			Log.d("INIT", "List ready");
			//setPic(linkToAllImage);
		} else {
			linkToAllImage = new PathFile();
			Log.d("INIT", "List NOT ready");
		}
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}

		selectedImage = new SendImage(linkToAllImage);
		
		mgrid.setSelected(true);
		mgrid.setSelector(R.drawable.ic_action_done);
		mgrid.setDrawSelectorOnTop(true);
		mgrid.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

		//Click in GridView
		mgrid.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Toast.makeText(ODA_Capture_ctivity.this, "" + position,
						Toast.LENGTH_SHORT).show();
				selectedImage.addIdItem(position);
			}
		});

		/* Display the menu */
		menuTitles = getResources().getStringArray(R.array.menu_array);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,GravityCompat.START);
		mDrawerList.setAdapter(new ArrayAdapter<String>(this,
				R.layout.drawer_list_item, menuTitles));
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
				// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
				// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			selectItem(1);
		}

	}

	/**
	 * Click to send all data
	 * 
	 * @param the
	 *            view v
	 */
	public void senddata(View v) {
		// If user logged redirect then send directly
		// if not redirect to login (switch case)
		Intent intent;
		if(isConnected){
			//Send Data
			intent = new Intent(this, SendActivity.class);
			startActivity(intent);
		}else{
			//Do Login
			intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
		}
		
	}

	/**
	 * Click to take a picture
	 * 
	 * @param the
	 *            View v
	 */
	public void takepicture(View v) {
		dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
	}

	/**
	 * Click to delete picture
	 * 
	 * @param the
	 *            View v
	 */
	public void deletepicture(View v) {
		PathFile p = (PathFile) selectedImage.getSelectedImage();
		SavePath sv = new SavePath(p);
		setPic(p);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.first, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Photo album for this application */
	private String getAlbumName() {
		return this.getString(R.string.dirImage);
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = mAlbumStorageDirFactory
					.getAlbumStorageDir(getAlbumName());

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name),
					"External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);
		return imageF;
	}

	private File setUpPhotoFile() throws IOException {

		File f = createImageFile();
		//mCurrentPhotoPath = f.getAbsolutePath();

		return f;
	}

	private void setPic(PathFile linkToAllimage) {

		/* There isn't enough memory to open up more than a couple camera photos */
		/* So pre-scale the target bitmap into which the file is decoded */

		/* Get the size of the ImageView */
		int targetW = mImageView.getWidth();
		int targetH = mImageView.getHeight();

		/* Get the size of the image */
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(linkToAllimage.get(0), bmOptions);
		int photoW = bmOptions.outWidth;
		int photoH = bmOptions.outHeight;

		/* Figure out which way needs to be reduced less */
		int scaleFactor = 1;
		if ((targetW > 0) || (targetH > 0)) {
			scaleFactor = Math.min(photoW / targetW, photoH / targetH);
		}

		/* Set bitmap options to scale the image decode target */
		bmOptions.inJustDecodeBounds = false;
		bmOptions.inSampleSize = scaleFactor;
		bmOptions.inPurgeable = true;

		/* Decode the JPEG file into a Bitmap */
		Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		mgrid.setAdapter(new MyAdapter(this, bmOptions, linkToAllimage));

	}

	private void galleryAddPic() {
		Intent mediaScanIntent = new Intent(
				"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
		File f = new File(mCurrentPhotoPath);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		this.sendBroadcast(mediaScanIntent);
	}

	private void dispatchTakePictureIntent(int actionCode) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		switch (actionCode) {
		case ACTION_TAKE_PHOTO_B:
			File f = null;

			try {
				f = setUpPhotoFile();
				mCurrentPhotoPath = f.getAbsolutePath();
				Log.d("LINK", mCurrentPhotoPath);
				linkToAllImage.add(mCurrentPhotoPath);
				//SavePath sv=new SavePath(linkToAllImage);
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(f));
			} catch (IOException e) {
				e.printStackTrace();
				f = null;
				mCurrentPhotoPath = null;
			}
			break;

		default:
			break;
		} // switch

		startActivityForResult(takePictureIntent, actionCode);
	}

	// small image view
	private void handleSmallCameraPhoto(Intent intent) {
		Bundle extras = intent.getExtras();
		mImageBitmap = (Bitmap) extras.get("data");
		mImageView.setImageBitmap(mImageBitmap);
		mImageView.setVisibility(View.VISIBLE);
	}

	// big image View
	private void handleBigCameraPhoto() {
		if (linkToAllImage.size() != 0) {
			setPic(linkToAllImage);
			galleryAddPic();
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case ACTION_TAKE_PHOTO_B: {
			if (resultCode == RESULT_OK) {
				SavePath sv = new SavePath(linkToAllImage);
				handleBigCameraPhoto();
			}
			break;
		} // ACTION_TAKE_PHOTO_B
		}
	}

	// Some lifecycle callbacks so that the image can survive orientation change
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
		outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY,(mImageBitmap != null));
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
		mImageView.setImageBitmap(mImageBitmap);
		mImageView
				.setVisibility(savedInstanceState
						.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? ImageView.VISIBLE
						: ImageView.INVISIBLE);
	}

	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	/**
	 * 
	 * @return the paths to file
	 */
	private PathFile init() {
		return new LoadImage().getPictures();
	}

	/**
	 * The click listner for ListView in the navigation drawer
	 */
	private class DrawerItemClickListener implements
	ListView.OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
				selectItem(position);
		}
	}


	private void selectItem(int position) {

		mDrawerList.setItemChecked(position, true);
		setTitle(menuTitles[position]);
		Toast.makeText(ODA_Capture_ctivity.this, "" + position,
				Toast.LENGTH_SHORT).show();
		mDrawerLayout.closeDrawer(mDrawerList);
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}
	

    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}
	
	/**
     * Fragment that appears in the "content_frame", shows a planet
     */
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.activity_capture, container, false);
//            int i = getArguments().getInt(ARG_PLANET_NUMBER);
//            String planet = getResources().getStringArray(R.array.menu_array)[i];
//
//            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
//                            "drawable", getActivity().getPackageName());
//            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
//            getActivity().setTitle(planet);
            return rootView;
        }
    }
}
